package com._21cn.cms.template.utils.label;

import com._21cn.cms.article.Constants;
import com._21cn.cms.article.entity.Article;
import com._21cn.cms.article.entity.ColumnArticle;
import com._21cn.cms.article.entity.RegionArticle;
import com._21cn.cms.article.entity.vo.ListArticle;
import com._21cn.cms.article.service.ArticleService;
import com._21cn.cms.article.service.ColumnArticleService;
import com._21cn.cms.article.service.RegionArticleService;
import com._21cn.cms.article.utils.ArticleUtil;
import com._21cn.framework.flip.PageHashMap;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.flip.PageTurn;
import com._21cn.framework.utils.ReflectUtil;
import com._21cn.framework.utils.StringUtil;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Thinkpad on 2017/4/9.
 */
@Component
public class ArticleListLabel {

    @Autowired
    private ColumnArticleService columnArticleService;

    @Autowired
    private RegionArticleService regionArticleService;

    @Autowired
    private ArticleService articleService;
    private ArticleListQuery articleListQuery = null;

    public void setArticleListQuery(ArticleListQuery articleListQuery){
        this.articleListQuery = articleListQuery;
    }

    public ArticleListQuery getArticleListQuery() {
        if (this.articleListQuery == null) {
            this.articleListQuery = new ArticleListQuery();
        }
        return this.articleListQuery;
    }

    public class ArticleListQuery{
        private Map<String, Object> params = new ConcurrentHashMap<String, Object>();
        private PageTurn pageTurn  = new PageTurn();
        private String service = null;

        /**
         * 对文章列表排序
         * @param order
         * @return
         */
        public ArticleListQuery order(String order){
            if( StringUtil.isEmpty(order) ){
                params.put("orderByClause", "PUBLISH_TIME DESC");
            }else{
                params.put("orderByClause", order);
            }
            return this;
        }

        /**
         * 对文章列表截取一定数量.
         * @return
         */
        public ArticleListQuery limit(int pageSize){
            return limit(1, pageSize);
        }

        public ArticleListQuery limit(int pageNo, int pageSize){
            params.put("pageNo", pageNo);
            params.put("pageSize", pageSize);
            return this;
        }

        /**
         * 文章含有图片
         * @return
         */
        public ArticleListQuery hasPicture(){
            params.put("eqPicFlag", Constants.PIC_FLAG_HAVE_PIC);
            return this;
        }

        /**
         * 文章含有首图
         * @return
         */
        public ArticleListQuery hasThumbPicture(){
            params.put("notNullThumbImgUrl", 1);
            return this;
        }

        /**
         * 文章在多少天内（发布时间）
         * @param days
         * @return
         */
        public ArticleListQuery ArticleInDays(int days) {
            params.put("gePublishDays", days);
            return this;
        }

        public PageTurn getPageTurn(){
            return pageTurn;
        }

        public void setPageNo( int pageNo ){
            params.put( "pageNo", pageNo );
            if( pageTurn != null )
                pageTurn.setPage( pageNo );
        }

        public void setPageSize(int pageSize) {
            this.params.put("pageSize", pageSize);
        }

        //设置查询默认值，可使查询语句简化
        private void initParam(){
            if( !params.containsKey( "inStatusList" ) ){
                List<Integer> statusList = new ArrayList<Integer>();
                statusList.add(Constants.PUBLISH_STATUS_DONE);
                statusList.add(Constants.PUBLISH_STATUS_FETCH_DONE);
                params.put("inPublishStatusList", statusList);
            }

            Integer pageSize = (Integer)params.get("pageSize");
            if(pageSize==null || pageSize.intValue()<=0){
                pageSize = 20;
                params.put("pageSize",pageSize);
            }

            Integer pageNo = (Integer)params.get("pageNo");
            if(pageNo==null || pageNo.intValue()<=0){
                pageNo = 1;
                params.put("pageNo",pageNo);
            }
            pageTurn = new PageTurn( pageNo, pageSize );

            Integer gePublishDays = (Integer) params.get("gePublishDays");
            if ((gePublishDays == null || gePublishDays.intValue() < 0)) {
                params.put("gePublishDays", 30);
            }

            if (gePublishDays != null && gePublishDays == 0){
                params.remove("gePublishDays");
            }

            String orderByClause = (String)params.get("orderByClause");
            if(StringUtil.isEmpty(orderByClause)){
                params.put("orderByClause", "TOP_TIME DESC, PUBLISH_TIME DESC");
            }
        }

        /**
         * 初始化结果
         * @param list
         * @return
         */
        private PageList<ListArticle> initResult( PageList<? extends ListArticle> list ){
            PageList<ListArticle> result = new PageList<ListArticle>();
            for(ListArticle listArticle: list){
                result.add( listArticle );
            }
            result.setPageTurn( list.getPageTurn() );
            return result;
        }

        public int count(){
            initParam();
            int rowCount = 0;
            if(service.equals("columnArticleService")){
                rowCount = columnArticleService.getCount( params );
            }
            if(service.equals("regionArticleService")){
                rowCount = regionArticleService.getCount( params );
            }
            if(service.equals("articleService")){
                rowCount = articleService.getCount( params );
            }
            pageTurn.initWithPage( pageTurn.getPage(), pageTurn.getPageSize(), rowCount );
            return rowCount;
        }

        /**
         * 查询文章基本信息
         * @return
         */
        public PageList<ListArticle> loadArticleBase(){
            initParam();
            PageList<ListArticle> result = new PageList<ListArticle>();
            result.setPageTurn( pageTurn );
            if( StringUtil.isEmpty(service) ){
                return result;
            }

            if( service.equals("columnArticleService") ){
                PageList<ColumnArticle> list = columnArticleService.getList(params, pageTurn.getPage(), pageTurn.getPageSize(), false);
                result = initResult(list);
            }else if( service.equals("regionArticleService") ){
                PageList<RegionArticle> list = regionArticleService.getList( params, pageTurn.getPage(), pageTurn.getPageSize(), false);
                result = initResult(list);
            }else if( service.equals("articleService") ){
                PageList<Article> list = articleService.getList( params, pageTurn.getPage(), pageTurn.getPageSize(), false);
                result = initResult(list);
            }

            return result;
        }

        /**
         * 查询文章附加信息
         * @return
         */
        public PageList<Article> loadArticleExt(){
            PageList<ListArticle> baseList = loadArticleBase();
            List<Integer> idList = ArticleUtil.getArticleIdList(baseList);
            PageList<Article> result = articleService.getListByIds(idList);
            for(Article article : result){
                for (ListArticle listArticle : baseList){
                    if (listArticle.getArticleId().equals(article.getId())){
                        article.setArticleUrl(listArticle.getArticleUrl());
                    }
                }
            }
            this.params.clear();
            return result;
        }

        /**
         * 查询本站文章附加信息
         * @return
         */
        public PageList<Article> loadArticleExtByHost(String host){
            PageList<ListArticle> baseList = loadArticleBase();
            List<Integer> idList = ArticleUtil.getArticleIdList(baseList);
            PageList<Article> result = articleService.getListByIds(idList);
            for (Article article : result){
                Integer articleId = article.getId();
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("eqArticleId", articleId);
                List<ColumnArticle> list = columnArticleService.getList(params, 1, 100, false);
                for( ColumnArticle columnArticle : list ){
                    if(columnArticle.getArticleUrl().contains(host)){
                        article.setArticleUrl(columnArticle.getArticleUrl());
                    }
                }
            }
            this.params.clear();
            return result;
        }

    }

    /**
     * 获取一些ID栏目的文章列表
     * @param ids 多个栏目ID,用逗号隔开，最多10个
     * @return
     */
    public ArticleListQuery column(String ids){
        ArticleListQuery articleListQuery = new ArticleListQuery();
        List<Integer> inStatusList = new ArrayList<Integer>();
        inStatusList.add(Constants.PUBLISH_STATUS_DONE);
        inStatusList.add(Constants.PUBLISH_STATUS_FETCH_DONE);
        articleListQuery.params.put("inPublishStatusList", inStatusList);
        articleListQuery.params.put("groupByClause", "ARTICLE_ID");
        List<Integer> inColumnIdList = StringUtil.str2IntList(ids);

        if(!inColumnIdList.isEmpty()){
            articleListQuery.service = "columnArticleService";
            if(inColumnIdList.size()==1){
                Integer id = inColumnIdList.get(0);
                articleListQuery.params.put("eqColumnId", id );
            }else {
                articleListQuery.params.put( "inColumnIdList", inColumnIdList );
            }
        }
        return articleListQuery;
    }

    /**
     * 获取一些ID频道的文章列表
     * @return
     */
    public ArticleListQuery channel(String ids){
        ArticleListQuery articleListQuery = new ArticleListQuery();
        List<Integer> inStatusList = new ArrayList<Integer>();
        inStatusList.add(Constants.PUBLISH_STATUS_DONE);
        inStatusList.add(Constants.PUBLISH_STATUS_FETCH_DONE);
        articleListQuery.params.put("inPublishStatusList", inStatusList);
        List<Integer> inChannelIdList = StringUtil.str2IntList(ids);

        if(!inChannelIdList.isEmpty()){
            articleListQuery.service = "articleService";
            articleListQuery.params.put("gePublishDays", 365);
            if(inChannelIdList.size()==1){
                Integer id = inChannelIdList.get(0);
                articleListQuery.params.put("eqChannelId", id );
            }else {
                articleListQuery.params.put( "inChannelIdList", inChannelIdList );
            }
        }
        return articleListQuery;
    }

    /**
     * 获取一些ID区块的文章列表
     * @return
     */
    public ArticleListQuery region(String ids){
        ArticleListQuery articleListQuery = new ArticleListQuery();
        List<Integer> inStatusList = new ArrayList<Integer>();
        inStatusList.add(Constants.PUBLISH_STATUS_DONE);
        inStatusList.add(Constants.PUBLISH_STATUS_FETCH_DONE);
        articleListQuery.params.put("inPublishStatusList", inStatusList);
        List<Integer> inRegionIdList = StringUtil.str2IntList(ids);

        if(!inRegionIdList.isEmpty()){
            articleListQuery.service = "regionArticleService";
            if(inRegionIdList.size()==1){
                Integer id = inRegionIdList.get(0);
                articleListQuery.params.put("eqRegionId", id );
            }else {
                articleListQuery.params.put( "inRegionIdList", inRegionIdList );
            }
        }
        return articleListQuery;
    }

}
